package com.atguigu.spring.controller;

import com.atguigu.spring.entity.Farmer;
import com.atguigu.spring.entity.Student;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class DemoController {

    @RequestMapping("/save/student")
    public List<String> saveStudent(
            Student student,

            // 数据绑定结果
            // BindingResult 对象必须和 Student 对象紧挨着，中间不能声明别的参数，否则 BindingResult 无效
            BindingResult result) {

        // 检查前面执行数据绑定操作是否有错误
        if (result.hasErrors()) {
            List<FieldError> fieldErrors = result.getFieldErrors();
            List<String> errorMsgList = fieldErrors.stream()
                    .map(fieldError -> {

                        String fieldName = fieldError.getField();
                        Object rejectedValue = fieldError.getRejectedValue();
                        String defaultMessage = fieldError.getDefaultMessage();

                        return "字段名称：" + fieldName + " 输入数值：" + rejectedValue + " 错误信息：" + defaultMessage;
                    }).collect(Collectors.toList());

            // 整合好错误信息之后，把错误信息作为响应体返回
            return errorMsgList;
        }

        System.out.println("student = " + student);
        return Arrays.asList("ok");
    }

    @RequestMapping("/save/farmer")
    public String saveFarmer(@RequestBody Farmer farmer) {
        System.out.println("farmer = " + farmer);
        return "ok";
    }
}
